package com.ourteam.education.api;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ourteam.education.dao.ClassroomDAOQueryBean;
import com.ourteam.education.dao.TeacherCampusRelateDAOFactory;
import com.ourteam.education.dao.TeacherCampusRelateDAOQueryBean;
import com.ourteam.education.dao.TeacherDAOQueryBean;
import com.ourteam.education.domain.ClassroomBean;
import com.ourteam.education.domain.TeacherBean;
import com.ourteam.education.service.ITeacherManageService;
import com.ourteam.frame.controller.AbstractCRUDServiceController;

@Controller
@CrossOrigin
@RequestMapping("/api/EDUCATION/teacher")
public class TeacherManagerAPI
		extends AbstractCRUDServiceController<TeacherDAOQueryBean, TeacherSearchBean, TeacherBean> {

	@Autowired
	private ITeacherManageService teacherService;

	@Override
	protected TeacherDAOQueryBean newQueryBean() {
		return new TeacherDAOQueryBean();
	}

	@Override
	protected int queryCount(TeacherDAOQueryBean queryBean) throws Exception {
		return 0;
	}

	@Override
	protected TeacherBean[] queryData(TeacherDAOQueryBean queryBean) throws Exception {
		return teacherService.queryTeachers(queryBean);
	}

	@Override
	protected void deleteData(long[] ids) throws Exception {
		teacherService.deleteTeachers(ids);
	}

	@Override
	protected TeacherBean getDataById(long id) throws Exception {
		return teacherService.getTeacherById(id);
	}

	@Override
	protected void saveData(TeacherBean dataBean) throws Exception {

		if (dataBean.getId() == 0) {
			teacherService.addNewTeacher(dataBean);
		} else {
			teacherService.modifyTeacher(dataBean);
		}

	}

	@RequestMapping("/list")
	@ResponseBody
	public TeacherBean[] list(final @RequestParam(required = false) String teacherName,
			final @RequestParam(required = false) String status, final @RequestParam(required = false) Long campusId)
			throws Exception {

		TeacherDAOQueryBean searchBean = new TeacherDAOQueryBean();

		TeacherDAOQueryBean.Criteria criteria = searchBean.createCriteria();

		if (StringUtils.isNoneBlank(status)) {
			criteria.andStatusEqualTo(status);
		}

		if (StringUtils.isNoneBlank(teacherName)) {
			criteria.andTeacherNameLike(teacherName);
		}

		if (campusId != null && campusId.longValue() != 0) {
			TeacherCampusRelateDAOQueryBean relateQueryBean = new TeacherCampusRelateDAOQueryBean();

			relateQueryBean.setDistinct(true);

			relateQueryBean.addTeacherIdSelectProperty();

			relateQueryBean.createCriteria().andCampusIdEqualTo(campusId);

			criteria.andIdIn(relateQueryBean, TeacherCampusRelateDAOFactory.getTeacherCampusRelateDAO());
		}

		return teacherService.queryTeachers(searchBean);
	}

}
